<template>
    <!-- <div class="control-bar">control-bar</div>  -->
    <div>
        <table class="file_browser_table">
            <thead>
                <tr>
                    <td colspan="5">
                        <div class="header-container">
                            <section>
                                <p class="breadcrumb-container">
                                    <span
                                        class="breadcrumb-item"
                                        v-for="item in compControl.compute_breadcrumb">
                                        <span
                                            class="item link"
                                            @click="tableControl.hanldeUpdateData(item.path, true)">
                                            {{ item.name }}
                                        </span>
                                        <span
                                            v-if="!item.is_last"
                                            class="divider"
                                            :class="item.divider_link ? 'link' : ''"
                                            @click="
                                                item.divider_link
                                                    ? tableControl.hanldeUpdateData(item.path, true)
                                                    : false
                                            ">
                                            /
                                        </span>
                                    </span>
                                </p>
                            </section>
                            <section>
                                <n-space>
                                    <n-popover trigger="hover">
                                        <template #trigger>
                                            <n-button
                                                size="tiny"
                                                @click="
                                                    tableControl.hanldeUpdateData(
                                                        tableControl.currentPath,
                                                        true
                                                    )
                                                ">
                                                <n-icon><RefreshFilled /></n-icon>
                                            </n-button>
                                        </template>
                                        <span>刷新</span>
                                    </n-popover>
                                    <com_btnModal_filePackup
                                        :parent="tableControl.currentPath"
                                        :data="compControl.fileOperation.computed_selected_data" />
                                    <com_btnModal_fileSetting
                                        @update:options="compControl.fileSetting.handleUpdateOption" />
                                </n-space>
                            </section>
                        </div>
                    </td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="col-selection"></td>
                    <td class="col-filename">
                        <p @click="tableControl.handleFileClick(tableControl.currentData[0])">..</p>
                    </td>
                    <td class="col-size">尺寸</td>
                    <td class="col-owner">所有者</td>
                    <td class="col-operation"></td>
                </tr>
                <tr
                    v-for="(item, index) in tableControl.currentData.slice(1, undefined)"
                    :key="item.path_name">
                    <td class="col-selection">
                        <n-checkbox
                            :checked="item.selected"
                            :on-update:checked="
                                (c: boolean) => {
                                    item.selected = c
                                }
                            "
                            v-if="item.type != 'parent'" />
                    </td>
                    <td class="col-filename">
                        <p v-if="item.type == 'parent'">..</p>
                        <p
                            v-else
                            @click="tableControl.handleFileClick(item)"
                            style="display: inline-flex; align-items: center">
                            <n-icon size="small" v-if="item.type == 'folder'">
                                <FolderOpenOutlined />
                            </n-icon>
                            <n-icon size="small" v-if="item.type == 'file'">
                                <AttachFileFilled />
                            </n-icon>
                            {{ item.path_name }}
                        </p>
                    </td>
                    <td class="col-size">
                        <p v-if="item.type != 'parent'">
                            {{ compControl.computed_size(item.size || 0) }}
                        </p>
                    </td>
                    <td class="col-owner">{{ item.owner }}</td>
                    <td class="col-operation" :id="'5d76e412-' + index">
                        <n-popconfirm
                            size="small"
                            trigger="hover"
                            :positive-text="null"
                            :negative-text="null"
                            :disabled="!compControl.fileSetting.options.download_alert">
                            <template #trigger>
                                <n-button
                                    v-if="
                                        compControl.fileSetting.options.click_download &&
                                        item.type == 'file'
                                    "
                                    @click="
                                        compControl.fileSetting.options.download_alert
                                            ? false
                                            : compControl.fileOperation.hanldeDownload(item.path_name)
                                    "
                                    size="tiny"
                                    circle>
                                    <n-icon><DownloadRound /></n-icon>
                                </n-button>
                                <span v-else></span>
                            </template>
                            <template #action></template>
                            <template #default>
                                <span>确认下载？</span>
                                <n-button
                                    size="tiny"
                                    type="primary"
                                    @click="compControl.fileOperation.hanldeDownload(item.path_name)">
                                    确认
                                </n-button>
                            </template>
                        </n-popconfirm>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script setup lang="ts">
import {
    axg_getDirectoryList,
    generate_download_link,
    type DirectoryItem
} from '@/utils/interface/Directory'

import { computed, onMounted, reactive } from 'vue'
import { FolderOpenOutlined, AttachFileFilled, DownloadRound, RefreshFilled } from '@vicons/material'
import { url_join } from '@/utils/tools/url-join'
import com_btnModal_fileSetting from './com_btnModal_fileSetting.vue'
import com_btnModal_filePackup from './com_btnModal_filePackup.vue'

const tableControl = reactive({
    currentData: [] as DirectoryItem[],
    currentPath: '',
    async handleFileClick(item: DirectoryItem) {
        if (item.type == 'parent') {
            tableControl.hanldeUpdateData(item.path_name, true)
        } else if (item.type == 'folder') {
            tableControl.hanldeUpdateData(item.path_name, false)
        } else {
        }
    },
    async hanldeUpdateData(path_name: string = '', is_abs_path: boolean = false) {
        if (!is_abs_path) {
            path_name = url_join(tableControl.currentPath, path_name ? `/${path_name}` : '')
        }

        const t = await axg_getDirectoryList(path_name)

        //TODO 首次空传参应当返回可访问的目录
        if (path_name == '') {
            tableControl.currentPath = t[0].path_name
        }
        tableControl.currentData = t || []
        tableControl.currentPath = path_name
    }
})
const compControl = reactive({
    compute_breadcrumb: computed<Array<BreadcrumbItem>>(() => {
        const parts = tableControl.currentPath.split('/').filter((part) => part !== '')
        const breadcrumbs = parts.map((part, index) => {
            const path = '/' + parts.slice(0, index + 1).join('/')
            const item: BreadcrumbItem = {
                name: part,
                path: path
            }
            if (index == parts.length - 1) {
                item.is_last = true
            }
            return item
        })
        // 添加根目录标识
        breadcrumbs.unshift({
            name: '',
            path: '/',
            divider_link: true
        })
        return breadcrumbs
    }),
    computed_size: computed(() => {
        return (size: number) => {
            if (size > 1024 * 1024 * 1024) {
                return (size / 1024 / 1024 / 1024).toFixed(0) + 'GiB'
            } else if (size > 1024 * 1024) {
                return (size / 1024 / 1024).toFixed(1) + 'MiB'
            } else if (size > 0 && size <= 1024) {
                return (size / 1024).toFixed(1) + 'KiB'
            } else {
                return '/'
            }
        }
    }),
    fileSetting: {
        options: { click_download: true, download_alert: true },
        handleUpdateOption: (options: any) => {
            compControl.fileSetting.options = options
        }
    },
    fileOperation: {
        hanldeDownload: (filename: string) => {
            const link = generate_download_link(tableControl.currentPath, filename)
            const a = document.createElement('a')
            a.href = link
            a.download = filename
            a.style.display = 'none'
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
        },
        computed_selected_data: computed(() => {
            return tableControl.currentData.filter((item) => item.selected == true)
        }),

        hanldeRename: () => {
            console.log('hanldeRename')
        }
    }
})
interface BreadcrumbItem {
    name: string
    path: string
    divider_link?: boolean
    is_last?: boolean
}

onMounted(() => {
    tableControl.hanldeUpdateData()
})
</script>

<style lang="scss" scoped>
@use './browser.scss';
:deep(.n-popconfirm__action) {
    margin-top: 0 !important;
}
</style>
